package org.goodsmanager.service;

import cn.hutool.core.lang.UUID;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.goodsmanager.entity.Category;
import org.goodsmanager.mapper.CategoryMapper;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;

/**
 * 分类Service实现类
 *
 * @author Goods Manager System
 * @version 1.0.0
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class CategoryService {

    private final CategoryMapper categoryMapper;

    /**
     * 添加分类
     */
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(value = "categories", allEntries = true)
    public boolean addCategory(Category category) {
        try {
            category.setId(UUID.randomUUID().toString());
            if (category.getSortOrder() == null) {
                category.setSortOrder(0);
            }
            if (category.getIsActive() == null) {
                category.setIsActive(1);
            }
            int result = categoryMapper.insert(category);
            log.info("添加分类成功: {}", category.getCategoryName());
            return result > 0;
        } catch (Exception e) {
            log.error("添加分类失败", e);
            throw new RuntimeException("添加分类失败: " + e.getMessage());
        }
    }

    /**
     * 更新分类
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean updateCategory(Category category) {
        try {
            int result = categoryMapper.update(category);
            log.info("更新分类成功: {}", category.getCategoryName());
            return result > 0;
        } catch (Exception e) {
            log.error("更新分类失败", e);
            throw new RuntimeException("更新分类失败: " + e.getMessage());
        }
    }

    /**
     * 删除分类
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteCategory(String id) {
        try {
            // 检查是否有商品使用该分类
            int productCount = categoryMapper.countProductsByCategory(id);
            if (productCount > 0) {
                log.warn("分类下有商品，无法删除, ID: {}", id);
                return false;
            }
            int result = categoryMapper.deleteById(id);
            log.info("删除分类成功, ID: {}", id);
            return result > 0;
        } catch (Exception e) {
            log.error("删除分类失败", e);
            throw new RuntimeException("删除分类失败: " + e.getMessage());
        }
    }

    /**
     * 根据ID查询分类
     */
    public Category getCategoryById(String id) {
        try {
            return categoryMapper.selectById(id);
        } catch (Exception e) {
            log.error("查询分类失败", e);
            throw new RuntimeException("查询分类失败: " + e.getMessage());
        }
    }

    /**
     * 查询所有分类
     */
    public List<Category> getAllCategories() {
        try {
            return categoryMapper.selectAll();
        } catch (Exception e) {
            log.error("查询所有分类失败", e);
            throw new RuntimeException("查询所有分类失败: " + e.getMessage());
        }
    }

    /**
     * 查询启用的分类
     */
    @Cacheable(value = "categories", key = "'active'")
    public List<Category> getActiveCategories() {
        try {
            return categoryMapper.selectActive();
        } catch (Exception e) {
            log.error("查询启用分类失败", e);
            throw new RuntimeException("查询启用分类失败: " + e.getMessage());
        }
    }
}